package com.ruoyi.quartz.task;

import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.constant.SysConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.mapper.SysTaskUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;


/**
 * 用户定时任务
 *
 * @author YJF
 */
@Component("userTask")
@Slf4j
public class UserTask {
    @Autowired
    private SysTaskUserMapper taskUserMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 更新用户在线状态-离线
     */
    public void updateOnlineStatus() {
        //首次登录
        Map<String, String> onlineFirst = redisCache.hGetAll(RedisConstants.ONLINE_FIRST);
        Long[] ids = new Long[onlineFirst.size()];
        int j = 0;
        for (String key : onlineFirst.keySet()) {
            ids[j] = Long.valueOf(key);
            //删除key
            redisCache.delCacheMapValue(RedisConstants.ONLINE_FIRST, key);
            j++;
        }
        if (ids.length > 0) {
            SysUser sysUser = new SysUser();
            sysUser.setUserIds(ids);
            sysUser.setOnlineStatus(SysConstants.CONSTANT_STR0);
            taskUserMapper.updateTaskOnlineStatus(sysUser);
        }
        //离线
        Map<String, String> checkOnline = redisCache.hGetAll(RedisConstants.CHECK_ONLINE);
        Long[] userIds = new Long[checkOnline.size()];
        int i = 0;
        for (String key : checkOnline.keySet()) {
            //时间戳差
            Long diffTime = DateUtils.getNowDate().getTime() / 1000 - Long.valueOf(String.valueOf(checkOnline.get(key)));
            if (diffTime > SysConstants.CHECK_ONLINE_DIFF) {
                userIds[i] = Long.valueOf(key);
                i++;
                //删除key
                redisCache.delCacheMapValue(RedisConstants.CHECK_ONLINE, key);
                //删除工作模式
                redisCache.delCacheMapValue(RedisConstants.WORK_PATTERN, key);
            }
        }
        if (StringUtils.isNotNull(userIds[0])) {
            SysUser sysUser = new SysUser();
            sysUser.setUserIds(userIds);
            sysUser.setOnlineStatus(SysConstants.CONSTANT_STR1);
            taskUserMapper.updateTaskOnlineStatus(sysUser);
        }

        log.info("更新用户离线状态", userIds.toString());
        System.out.println("更新用户在线状态方法");
    }
}
